//
//  ShaiWuVC.m
//  MyTest
//
//  Created by zhiyou on 16-4-12.
//  Copyright (c) 2016年 wangyang. All rights reserved.
//

#import "ShaiWuVC.h"
#import "ShaiWu.h"
#import "ShaiWuCell.h"
#import "PublishVC.h"
#define BASE_URL_TOTAL @"http://www.shihuo.cn/app2/shaiwuList?platform=ios&timestamp=1460375095&v=4.0.2&token=d7e7edafd8ead813ed66d8926614a2aa&isHot=0&page=1"
#define BASE_URL_ELITE @"http://www.shihuo.cn/app2/shaiwuList?platform=ios&timestamp=1460375169&v=4.0.2&token=d740b73df726861902c577ee708f7c1b&isHot=1&page=1"
#define BASE_STR1 @"http://www.shihuo.cn/app2/shaiwuList?platform=ios&timestamp=1460375095&v=4.0.2&token=d7e7edafd8ead813ed66d8926614a2aa&isHot=0&page="
#define BASE_STR2 @"http://www.shihuo.cn/app2/shaiwuList?platform=ios&timestamp=1460375169&v=4.0.2&token=d740b73df726861902c577ee708f7c1b&isHot=1&page="
@interface ShaiWuVC () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate>
{
    float _lastOffSetY;
    UIButton *_lastBtn;
    NSString *_url;
}
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIButton *photoBtn;
@property (nonatomic, assign) int count;
@property (nonatomic, copy)   NSString *url;
@end

@implementation ShaiWuVC
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"晒物频道";
    _dataArray = [[NSMutableArray alloc] init];
    self.count = 2;
    self.url = BASE_STR1;
    
    [self createButton];
    [self setPhotoBtn];
    [self getData:BASE_URL_TOTAL];
    [self.view addSubview:self.collectionView];
    [self.view bringSubviewToFront:_photoBtn];
    
    [self addPullWithUrl:self.url];
    [self addInfiniteWithUrl:self.url];
    
}
- (void)setPhotoBtn
{
    _photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _photoBtn.center = CGPointMake(Width/2, Height*5/6);
    _photoBtn.bounds = CGRectMake(0, 0, 50, 50);
    _photoBtn.backgroundColor = [UIColor redColor];
    _photoBtn.layer.cornerRadius = 22;
    _photoBtn.clipsToBounds = YES;
    [_photoBtn setBackgroundImage:[UIImage imageNamed:@"shangchuanpic"] forState:UIControlStateNormal];
    [_photoBtn addTarget:self action:@selector(selectPhoto) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_photoBtn];
    
}
- (void)showPhoto
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1];
    _photoBtn.center = CGPointMake(Width/2, Height*5/6);
    _photoBtn.bounds = CGRectMake(0, 0, 50, 50);
    [UIView commitAnimations];
}
- (void)hidePhoto
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1];
    _photoBtn.center = CGPointMake(-100, Height*5/6);
    _photoBtn.bounds = CGRectMake(0, 0, 50, 50);
    [UIView commitAnimations];
}
- (void)selectPhoto
{
    PublishVC *vc = [[PublishVC alloc] init];
    [self presentViewController:vc animated:YES completion:nil];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y < 0) {
        [self addPullWithUrl:BASE_STR1];
    }
    if (scrollView.contentOffset.y - _lastOffSetY > 0) {
        
        [self hidePhoto];
    }else
    {
        [self showPhoto];
    }
    _lastOffSetY = scrollView.contentOffset.y;
}
#pragma mark -- UICollectionViewDataSource, UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ShaiWuCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ShaiWuCell" forIndexPath:indexPath];
    ShaiWu *shaiWu = _dataArray[indexPath.row];
    cell.contentView.backgroundColor = [UIColor whiteColor];
    cell.shaiWu = shaiWu;
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((Width-30)/2, Height*2/5);
}

#pragma mark -- 获取数据
- (void)getData:(NSString *)url
{
    [MyRequest getWithURL:url parameters:nil success:^(NSDictionary *dic) {
        NSDictionary *dictionary = [dic objectForKey:@"data"];
        NSArray *arr = [dictionary objectForKey:@"list"];
        for (NSDictionary *dic in arr) {
            ShaiWu *shaiWu = [[ShaiWu alloc] initWithDictionary:dic];
            [_dataArray addObject:shaiWu];
        }
        [_collectionView reloadData];
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}
- (void)getData
{
    NSString *url = [NSString stringWithFormat:@"%@%d",_url,1];
    [MyRequest getWithURL:url parameters:nil success:^(NSDictionary *dic) {
        NSDictionary *dictionary = [dic objectForKey:@"data"];
        NSArray *arr = [dictionary objectForKey:@"list"];
        [_dataArray removeAllObjects];
        for (NSDictionary *dic in arr) {
            ShaiWu *shaiWu = [[ShaiWu alloc] initWithDictionary:dic];
            [_dataArray addObject:shaiWu];
        }
        [_collectionView reloadData];
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}
#pragma mark -- 创建按钮
- (void)createButton
{
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, Width, 40)];
    [self.view addSubview:bgView];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, Width, 40)];
    imageView.image = [UIImage imageNamed:@"bg_toolbar"];
    [bgView addSubview:imageView];
    
    UIButton *totalBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    totalBtn.frame = CGRectMake(0, 0, Width/2, 40);
    [totalBtn setTitle:@"全部" forState:UIControlStateNormal];
    [totalBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    totalBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    totalBtn.tag = 100;
    [totalBtn addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:totalBtn];
    
    UIButton *eliteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    eliteBtn.frame = CGRectMake(Width/2, 0, Width/2, 40);
    [eliteBtn setTitle:@"精华" forState:UIControlStateNormal];
    eliteBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [eliteBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    eliteBtn.tag = 200;
    [eliteBtn addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:eliteBtn];
}
- (void)clickButton:(UIButton *)button
{
    if (_lastBtn == button) {
        return;
    }else {
        self.count = 1;
    }
    if (button.tag == 100)
    {
        _url = BASE_STR1;
        _dataArray = [[NSMutableArray alloc] init];
        [self getData:BASE_URL_TOTAL];
        [self addInfiniteWithUrl:self.url];
    }else {
        _url = BASE_STR2;
        _dataArray = [[NSMutableArray alloc] init];
        [self getData:BASE_URL_ELITE];
        [self addInfiniteWithUrl:self.url];
    }
    _lastBtn = button;
}

#pragma mark -- 下拉加载

- (void)addPullWithUrl:(NSString *)url
{
    __weak ShaiWuVC * mySelf = self;
    
    [_collectionView addHeaderWithCallback:^{
        
        [mySelf getData];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [mySelf.collectionView headerEndRefreshing];
        });
    }];
    
   //[self.collectionView headerBeginRefreshing];
}
#pragma mark -- 上拉刷新

- (void)addInfiniteWithUrl:(NSString *)url
{
    __weak ShaiWuVC * mySelf = self;

    [self.collectionView addFooterWithCallback:^{
        
        [mySelf getData:[NSString stringWithFormat:@"%@%d",url,mySelf.count]];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 结束刷新
            [mySelf.collectionView footerEndRefreshing];
            mySelf.count ++;
        });
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- 创建collectionView
- (UICollectionView *)collectionView
{
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 104, Width, Height-104-49) collectionViewLayout:layout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor lightGrayColor];
        [_collectionView registerClass:[ShaiWuCell class] forCellWithReuseIdentifier:@"ShaiWuCell"];
    }
    return _collectionView;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
